﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MakeIT_Bill_Maker
{
    public partial class EditApartment : Form
    {
        // Data Connection
        private Database.DatabaseConnection db = new Database.DatabaseConnection();
        private DataSet ds;
        private string sql;
        private DataTable dt;

        public EditApartment()
        {
            InitializeComponent();
        }

        // Form Load
        private void EditApartment_Load(object sender, EventArgs e)
        {
            sql = "SELECT AptNo FROM Users";
            ds = db.Show(sql);
            dt = ds.Tables[0];
            foreach (DataRow row in dt.Rows)
            {
                cmbAptNo.Items.Add(row[0]);
            }
        }

        // When the text in 'cmbAptNo' changes
        private void cmbAptNo_TextChanged(object sender, EventArgs e)
        {
            string AptNo = cmbAptNo.Text;

            sql = "SELECT AptNo, Name, MeterNo FROM Users WHERE AptNo='" + AptNo + "'";
            ds = db.Show(sql);
            dt = ds.Tables[0];
            foreach (DataRow row in dt.Rows)
            {
                txtName.Text = row[1].ToString();
                txtMeterNo.Text = row[2].ToString();
            }       
        }

        // 'Edit' button
        private void btnEdit_Click(object sender, EventArgs e)
        {
            string aptNo = cmbAptNo.Text;
            string aptNameEdited = txtName.Text;
            string meterNoEdited = txtMeterNo.Text;

            if (aptNo == "" || aptNameEdited == "" || meterNoEdited == "")
            {
                MessageBox.Show("All the fields must be filled.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                sql = "UPDATE Users SET Name = '" + aptNameEdited + "',MeterNo = '" + meterNoEdited + "' WHERE AptNo='" + aptNo + "'";
                bool b = db.edit(sql);
                if (b == true)
                {
                    MessageBox.Show("Value updated succesfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Failed to update the value.", "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        // 'Next' button
        private void btnNext_Click(object sender, EventArgs e)
        {
            cmbAptNo.Text = "";
            txtName.Clear();
            txtMeterNo.Clear();
        }
    }
}
